﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using _404park.ApplicationServices.Crawler.Parser;
using _404park.Core.Crawler;

namespace _404park.ApplicationServices.Crawler
{
    public class StoryCrawler : IResultProvider
    {
        private FeedParserManager _parserManager;

        private readonly string[] _searchProviders = { "GoogleCSE", "Bing", "YouTube", "Ebay", "Flickr", "Wikipedia"};

        public string[] Providers { 
            get { 
                return new string[]{
                    "BBC", "CNN", "Ebay", 
				    "ESPN", "Flickr", "HuffingtonPost", 
				    "PeopleMagazine", "TMZ", "Twitter", 
				    "Wikipedia", "Yahoo", "Youtube"};
        } }

        public StoryCrawler()
		{
			_parserManager = new FeedParserManager();
		}

		public IList<Feed> GetSearchResults(string keyword)
		{
			return GetSearchResults(keyword, Providers);
		}

		public IList<Feed> GetSearchResults(string keyword, string[] providers)
		{
			var results = new List<Feed>();

			foreach (string provider in providers)
			{
				var parser = _parserManager.GetParser(provider);
				if (parser != null){
					var feeds = parser.GetFeeds(keyword);
					if (feeds != null && feeds.Count > 0)
						results.AddRange(feeds);
				}					
			}

			return results;
		}

        public IList<Feed> GetSearchResults(string keyword, string[] providers, int start)
        {
            var results = new List<Feed>();

            foreach (string provider in providers)
            {
                var parser = _parserManager.GetParser(provider);
                if (parser != null)
                {
                    var feeds = parser.GetFeeds(keyword, start);
                    if (feeds != null && feeds.Count > 0)
                        results.AddRange(feeds);
                }
            }

            return results;
        }

        public IList<Feed> GetSelfHostedSearchResults(string keyword, int start, int expectedCount)
        {
            var results = new List<Feed>();

            foreach (string provider in _searchProviders)
            {
                var parser = _parserManager.GetParser(provider);
                if (parser != null)
                {
                    var feeds = parser.GetFeeds(keyword);
                    if (feeds != null && feeds.Count > 0)
                        results.AddRange(feeds);
                    if (feeds.Count >= expectedCount)
                        break;
                }
            }

            return results;
        }
    }
}
